package com.semlab.client.mvp.home.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckLayoutPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.semlab.client.app.gin.Injector;
import com.semlab.client.events.ClientLoginEvent;
import com.semlab.client.events.FBLoginEvent;
import com.semlab.client.fwk.Event;
import com.semlab.client.widgets.FBButton;
import com.semlab.client.widgets.LoadingIndicator;
import com.semlab.client.widgets.NumberTextBox;

public abstract class ImportPanel extends Composite {

    private static ImportPanelUiBinder uiBinder = GWT
            .create(ImportPanelUiBinder.class);

    interface ImportPanelUiBinder extends UiBinder<Widget, ImportPanel> {
    }

    @UiField
    NumberTextBox numberOfFriends;
    @UiField
    NumberTextBox numberOfMovies;
    @UiField
    HTMLPanel importSettingsPanel;
    @UiField
    FBButton fbButton;
    @UiField
    LoadingIndicator loading;
    @UiField
    DeckLayoutPanel deckPanel;

    public ImportPanel() {
        initWidget(uiBinder.createAndBindUi(this));
        Injector.INSTANCE.getEventBus().addHandler(ClientLoginEvent.TYPE, new Event.Handler<ClientLoginEvent>() {
            @Override
            public void on(ClientLoginEvent loginEvent) {
                fbButton.setVisible(false);
                if(!loginEvent.getClient().isImported()){
                    deckPanel.showWidget(1);
                }
                Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
                    @Override
                    public void execute() {
                        loading.hide();
                    }
                });
            }
        });
        Injector.INSTANCE.getEventBus().addHandler(FBLoginEvent.TYPE, new Event.Handler<FBLoginEvent>() {
            @Override
            public void on(FBLoginEvent loginEvent) {
                loading.showLoading("Gathering data");
            }
        });        fbButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                loading.showLoading("Contacting facebook");
            }
        });
        deckPanel.showWidget(0);
    }

    @UiHandler("startImport")
    void startImport(ClickEvent e) {
        loading.showLoading("Importing profile");
        startImport(numberOfFriends.getInt(), numberOfMovies.getInt());
    }

    public abstract void startImport(int friends, int movies);

}
